<%@taglib prefix="itrust" uri="/WEB-INF/tags.tld"%>
<%@page errorPage="/auth/exceptionHandler.jsp"%>

<%@page import="java.util.List"%>
<%@page import="java.util.Map"%>
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>

<%@page import="edu.ncsu.csc.itrust.EmailUtil"%>
<%@page import="edu.ncsu.csc.itrust.beans.OfficeVisitBean"%>
<%@page import="edu.ncsu.csc.itrust.beans.LabProcedureBean"%>
<%@page import="edu.ncsu.csc.itrust.beans.LOINCbean"%>
<%@page import="edu.ncsu.csc.itrust.beans.PatientReferralBean"%>
<%@page import="edu.ncsu.csc.itrust.dao.DAOFactory"%>
<%@page import="edu.ncsu.csc.itrust.beans.DiagnosisBean"%>
<%@page import="edu.ncsu.csc.itrust.beans.MedicationBean"%>
<%@page import="edu.ncsu.csc.itrust.beans.OverrideReasonBean"%>
<%@page import="edu.ncsu.csc.itrust.beans.ProcedureBean"%>
<%@page import="edu.ncsu.csc.itrust.beans.InstructionBean"%>
<%@page import="edu.ncsu.csc.itrust.beans.PrescriptionBean"%>
<%@page import="edu.ncsu.csc.itrust.beans.MessageBean"%>
<%@page import="edu.ncsu.csc.itrust.action.SendMessageAction"%>
<%@page import="edu.ncsu.csc.itrust.action.EditOfficeVisitAction"%>
<%@page import="edu.ncsu.csc.itrust.action.AddOfficeVisitAction"%>
<%@page import="edu.ncsu.csc.itrust.action.EditPrescriptionAction"%>
<%@page import="edu.ncsu.csc.itrust.action.PatientReferralAction"%>
<%@page import="edu.ncsu.csc.itrust.beans.forms.EditOfficeVisitForm"%>
<%@page import="edu.ncsu.csc.itrust.exception.iTrustException"%>
<%@page import="edu.ncsu.csc.itrust.beans.HospitalBean"%>
<%@page import="edu.ncsu.csc.itrust.BeanBuilder"%>
<%@page import="edu.ncsu.csc.itrust.exception.FormValidationException"%>
<%@page import="edu.ncsu.csc.itrust.beans.PersonnelBean"%>
<%@page import="edu.ncsu.csc.itrust.dao.mysql.PersonnelDAO"%>
<%@page import="edu.ncsu.csc.itrust.beans.PrescriptionBean"%>

<%@include file="/global.jsp"%>

<%
pageTitle = "iTrust - Document Office Visit";
%>

<%@include file="/header.jsp"%>

<%
	boolean createVisit = false;
	String ovIDString = request.getParameter("ovID");
	String pidString = (String)session.getAttribute("pid");
	
	if(ovIDString == null) {
		createVisit = true;
		AddOfficeVisitAction action = new AddOfficeVisitAction(prodDAO, pidString);
		ovIDString = "" + action.addEmptyOfficeVisit(loggedInMID.longValue());
		loggingAction.logEvent(TransactionType.OFFICE_VISIT_CREATE, loggedInMID, Long.parseLong(pidString), "Office Visit ID: " + ovIDString);
	}

	if (pidString == null || 1 > pidString.length()) {
		response.sendRedirect("/iTrust/auth/getPatientID.jsp?forward=hcp-uap/editOfficeVisit.jsp?ovID=" + ovIDString);
	   	return;
	}
	//Log office visit view
	loggingAction.logEvent(TransactionType.OFFICE_VISIT_VIEW, loggedInMID, Long.parseLong(pidString), "Office Visit ID: " + ovIDString);
    
	EditOfficeVisitAction action = new EditOfficeVisitAction(prodDAO, loggedInMID, pidString, ovIDString);
    EditPrescriptionAction action2 = new EditPrescriptionAction(prodDAO);
	long ovID = action.getOvID();
	OfficeVisitBean visit = action.getOfficeVisit();
	String confirm = "";
	String warning = "";
	if (request.getParameter("startDate") != null && request.getParameter("endDate") != null){
		warning = action2.hasInteraction(request.getParameter("addMedID"), pidString, request.getParameter("startDate"), request.getParameter("endDate"));
	}
		warning += action2.isAllergyOnList(pidString,request.getParameter("addMedID"));
	
	if ("true".equals(request.getParameter("formIsFilled"))) {
		EditOfficeVisitForm form = new BeanBuilder<EditOfficeVisitForm>().build(request.getParameterMap(), new EditOfficeVisitForm());
		if ("".equals(warning) || "true".equals(request.getParameter("checkPresc"))){			
			if ("true".equals(request.getParameter("checkPresc"))){
				form.setAddMedID(request.getParameter("testMed"));
				form.setStartDate(request.getParameter("medStart"));
				form.setDosage(request.getParameter("medDos"));
				form.setEndDate(request.getParameter("medEnd"));
				form.setInstructions(request.getParameter("medInst"));
				form.setOverrideCode(request.getParameterValues("overrideReasonCode"));
				form.setOverrideComment(request.getParameter("overrideComment"));
				String problem = action2.hasInteraction(request.getParameter("testMed"), pidString, request.getParameter("medStart"), request.getParameter("medEnd"));
				problem += action2.isAllergyOnList(pidString,request.getParameter("testMed"));
				new EmailUtil(prodDAO).sendEmail(action.makeEmailApp(loggedInMID,pidString,problem));
				
				//Log the interaction warning
				String ovrReason = request.getParameterValues("overrideReasonCode")[0];
				if (problem != "" || problem != null) {
					loggingAction.logEvent(TransactionType.OVERRIDE_INTERACTION_WARNING, loggedInMID, Long.parseLong(pidString), "Drug: "+ request.getParameter("testMed") +" Reason: " + ovrReason);
				}
				
			}
			
			form.setHcpID("" + visit.getHcpID());
			form.setPatientID("" + visit.getPatientID());
			try {
				confirm = action.updateInformation(form);
				
				// Logging for removals
				if(!"".equals(request.getParameter("removeLabProcID"))) {
					loggingAction.logEvent(TransactionType.REMOVE_LAB_PROCEDURE, loggedInMID, Long.parseLong(pidString), 
							"Procedure: " + request.getParameter("removeLabProcID"));
					loggingAction.logEvent(TransactionType.LAB_PROC_REMOVE, loggedInMID, Long.parseLong(pidString),
							"Procedure: " + request.getParameter("removeLabProcID"));
				}
				
				if(!"".equals(request.getParameter("removeProcID"))) {
					loggingAction.logEvent(TransactionType.REMOVE_PROCEDURE, loggedInMID, Long.parseLong(pidString), 
							"Procedure: " + request.getParameter("removeProcID"));
				}
				
				if(!"".equals(request.getParameter("removeDiagID"))) {
					loggingAction.logEvent(TransactionType.REMOVE_DIAGNOSIS, loggedInMID, Long.parseLong(pidString), 
							"Diagnosis: " + request.getParameter("removeDiagID"));
				}
				
				if(!"".equals(request.getParameter("removeImmunizationID"))) {
					loggingAction.logEvent(TransactionType.REMOVE_IMMUNIZATION, loggedInMID, Long.parseLong(pidString), 
							"Immunization: " + request.getParameter("removeImmunizationID"));
				}
				
				if(!"".equals(request.getParameter("removeMedID"))) {
					loggingAction.logEvent(TransactionType.REMOVE_PRESCRIPTION, loggedInMID, Long.parseLong(pidString), 
							"Prescription: " + request.getParameter("removeMedID"));
				}
				
				if(!"".equals(request.getParameter("removeInstructID"))) {
					loggingAction.logEvent(TransactionType.PATIENT_INSTRUCTIONS_REMOVE, loggedInMID, Long.parseLong(pidString),
							"Office Visit ID: " + ovID);
				}				
				
				if(!"".equals(request.getParameter("removeReferID"))) {
					loggingAction.logEvent(TransactionType.CANCEL_PATIENT_REFERRAL, loggedInMID, Long.parseLong(pidString),
							"Cancelled Referral, Office Visit ID: " + ovID);
				}	
				
				// Logging for adds
				if(!"".equals(request.getParameter("addLabProcID"))) {
					loggingAction.logEvent(TransactionType.ADD_LAB_PROCEDURE, loggedInMID, Long.parseLong(pidString), 
							"Procedure: " + request.getParameter("addLabProcID"));
					loggingAction.logEvent(TransactionType.LAB_PROC_CREATE, loggedInMID, Long.parseLong(pidString),
							"Procedure: " + request.getParameter("addLabProcID"));
				}
				
				else if(!"".equals(request.getParameter("addProcID"))) {
					loggingAction.logEvent(TransactionType.ADD_PROCEDURE, loggedInMID, Long.parseLong(pidString), 
							"Procedure: " + request.getParameter("addProcID"));
				}
				
				else if(!"".equals(request.getParameter("addDiagID"))) {
					loggingAction.logEvent(TransactionType.ADD_DIAGNOSIS, loggedInMID, Long.parseLong(pidString), 
							"Diagnosis: " + request.getParameter("addDiagID"));
				}
				
				else if(!"".equals(request.getParameter("addImmunizationID"))) {
					loggingAction.logEvent(TransactionType.ADD_IMMUNIZATION, loggedInMID, Long.parseLong(pidString), 
							"Diagnosis: " + request.getParameter("addImmunizationID"));
				}
				
				else if(!"".equals(request.getParameter("addInstName"))){
					loggingAction.logEvent(TransactionType.PATIENT_INSTRUCTIONS_ADD, loggedInMID, Long.parseLong(pidString),
							"Office Visit ID: "+ ovID );
				}
				
				else if(!"".equals(request.getParameter("referTo"))){
					loggingAction.logEvent(TransactionType.CREATE_PATIENT_REFERRAL, loggedInMID, Long.parseLong(pidString),
							"Office Visit ID: "+ ovID + ", Referred To: " + request.getParameter("referTo"));
				}
				
				else if ( request.getParameter("checkPresc").equals("true") || !"".equals(request.getParameter("addMedID"))){
						String loggingExtra = "";
						if(request.getParameterValues("overrideReasonCode") != null) {
							loggingExtra += ", Reason:";
							for(String reason : request.getParameterValues("overrideReasonCode"))
								loggingExtra += " " + reason;
						}
							
						if(request.getParameter("overrideComment") != null) {
							loggingExtra += ", Comment: " + request.getParameter("overrideComment");
						}
						loggingAction.logEvent(TransactionType.PRESCRIPTION_ADD, loggedInMID, Long.parseLong(pidString), 
								"Prescription: " + request.getParameter("testMed") + loggingExtra);
				} else {
					loggingAction.logEvent(TransactionType.OFFICE_VISIT_EDIT, loggedInMID, Long.parseLong(pidString), "Office Visit ID: " + ovIDString);
				}
			}
			catch (FormValidationException e) {
				e.printHTML(pageContext.getOut());
				confirm = "Input not valid";
			}
		}
	} else if(!createVisit) {
		loggingAction.logEvent(TransactionType.OFFICE_VISIT_VIEW, loggedInMID, Long.parseLong(pidString), "Office Visit ID: " + ovIDString);
	}
	OfficeVisitBean ov = action.getOfficeVisit();
	List<HospitalBean> hcpHospitals = action.getHospitals(ov.getHcpID());
	List <LabProcedureBean> lpBeans = action.getLabProcedures(Long.parseLong(pidString), ovID);
%>

<div align=center>
<%
if (!"".equals(confirm)) {
	if (request.getParameter("checkPresc").equals("false")){ %> <span
	class="iTrustMessage">Operation Canceled</span> <% } else if ("success".equals(confirm)) { 
			
	%> <span class="iTrustMessage">Information Successfully Updated</span>
<%	}
	else { %> <span class="iTrustError"><%= StringEscapeUtils.escapeHtml("" + (confirm)) %></span>
<%	}
}	
%>
</div>

<script type="text/javascript">
	function removeID(type, value) {
		document.getElementById(type).value = value;
		document.forms[0].submit();
	}

	function setVar(){
		var medID = document.getElementById("addMedID");
		var medIDindex = medID.options.selectedIndex;
		var medIDtxt = medID.options[medIDindex].value;
		var medDostxt = document.getElementById("dosage").value;
		var medStarttxt = document.getElementById("startDate").value;
		var medEndtxt = document.getElementById("endDate").value;
		var medInsttxt = document.getElementById("instructions").value;
		document.getElementById("testMed").value = medIDtxt;
		document.getElementById("medDos").value = medDostxt;
		document.getElementById("medStart").value = medStarttxt;
		document.getElementById("medEnd").value = medEndtxt;
		document.getElementById("medInst").value = medInsttxt;
		document.forms[0].submit();
	}

	function presCont(){
		document.getElementById("checkPresc").value = "true";
		document.forms[0].submit();
	}

	function presCanc(){
		var medID = document.getElementById("addMedID");
		var medIDindex = medID.options.selectedIndex;
		var medIDtxt = medID.options[medIDindex].value;
		var medDostxt = document.getElementById("dosage").value;
		var medStarttxt = document.getElementById("startDate").value;
		var medEndtxt = document.getElementById("endDate").value;
		var medInsttxt = document.getElementById("instructions").value;

		document.getElementById("testMed").value = "";
		document.getElementById("medDos").value = "";
		document.getElementById("medStart").value = "";
		document.getElementById("medEnd").value = "";
		document.getElementById("medInst").value = "";
		document.getElementById("checkPresc").value = "false";
		document.forms[0].submit();
	}
	
	function unhide(divID) {
		var item = document.getElementById(divID);
	 	if (item) {
	 		item.className=(item.className=='hidden')?'unhidden':'hidden';
	 	}
	 }
	
</script>

<form action="editOfficeVisit.jsp" method="post" id="mainForm">
<input type="hidden" name="formIsFilled" value="true" /> <input type="hidden"
	name="ovID" value="<%= StringEscapeUtils.escapeHtml("" + (ovID)) %>" />
<input type="hidden" id="removeDiagID" name="removeDiagID" value="" />
<input type="hidden" id="removeMedID" name="removeMedID" value="" /> 
<input type="hidden" id="removeProcID" name="removeProcID" value="" /> 
<input type="hidden" id="removeImmunizationID" name="removeImmunizationID"
	value="" /> <input type="hidden" id="removeLabProcID"
	name="removeLabProcID" value="" /> 
<input type="hidden" id="removeInstructID" name="removeInstructID" value"" /> 
<input type="hidden" id="removeReferID" name="removeReferID" value"" /> 
<input type="hidden" id="checkPresc" name="checkPresc" value="" /> 
<input type="hidden" id="testMed" name="testMed"
	value=<%= StringEscapeUtils.escapeHtml("" + (request.getParameter("testMed") )) %> />
<input type="hidden" id="medDos" name="medDos"
	value=<%= StringEscapeUtils.escapeHtml("" + (request.getParameter("medDos") )) %> />
<input type="hidden" id="medStart" name="medStart"
	value=<%= StringEscapeUtils.escapeHtml("" + (request.getParameter("medStart") )) %> />
<input type="hidden" id="medEnd" name="medEnd"
	value=<%= StringEscapeUtils.escapeHtml("" + (request.getParameter("medEnd") )) %> />
<input type="hidden" id="medInst" name="medInst"
	value=<%= StringEscapeUtils.escapeHtml("" + (request.getParameter("medInst") )) %> />

<div align=center>
<table class="fTable" align="center">
	<tr>
		<th colspan="2">Office Visit</th>
	</tr>
	<tr>
		<td class="subHeaderVertical">Patient ID:</td>
		<td><%= StringEscapeUtils.escapeHtml("" + (prodDAO.getAuthDAO().getUserName(ov.getPatientID()))) %>
		</td>
	</tr>
	<tr>
		<td class="subHeaderVertical">Date of Visit:</td>
		<td><input name="visitDate"
			value="<%= StringEscapeUtils.escapeHtml("" + (ov.getVisitDateStr())) %>" /><input
			type="button" value="Select Date"
			onclick="displayDatePicker('visitDate');" /></td>
	</tr>
	<tr>
		<td class="subHeaderVertical">Hospital:</td>
		<td><select name="hospitalID">
			<option value="">N/A</option>
			<%for(HospitalBean hos : hcpHospitals) {%>
			<option
				value="<%= StringEscapeUtils.escapeHtml("" + (hos.getHospitalID())) %>"
				<%= StringEscapeUtils.escapeHtml("" + (hos.getHospitalID().equals(ov.getHospitalID()) ? "selected=selected" : "")) %>>
			<%= StringEscapeUtils.escapeHtml("" + (hos.getHospitalName())) %></option>
			<%} %>
		</select></td>
	</tr>
	<tr>
		<td class="subHeaderVertical">Notes:</td>
		<td><textarea rows="4" style="width: 100%;" name="notes"><%= StringEscapeUtils.escapeHtml("" + (ov.getNotes())) %></textarea></td>
	</tr>
</table>
<br />
<input type="submit" name="update" id="update" value="Update">
</div>
<br />
<br />
<%@include file="/auth/hcp-uap/forms/PrescriptionForm.jsp"%>
<br />
<br />
<%@include file="/auth/hcp-uap/forms/LabProceduresForm.jsp"%>
<br />
<br />
<div align="center"><%@include
	file="/auth/hcp-uap/forms/DiagnosesForm.jsp"%>
<br />
<br />
<br />
<%@include file="/auth/hcp-uap/forms/ProceduresForm.jsp"%>
<br />
<br />
<br />
<%@include file="/auth/hcp-uap/forms/ImmunizationForm.jsp"%>
</div>
<br />
<br />
<div align=center><%@include
	file="/auth/hcp-uap/forms/InstructionForm.jsp"%>
</div>
<br />
<br />
<div align=center><%@include
	file="/auth/hcp-uap/forms/PatientReferralsForm.jsp"%>
</div>

<br />
<br />
<br />
<itrust:patientNav /> <br />

</form>

<%@include file="/footer.jsp"%>
